package com.umeox.moto.common.extension

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import java.util.Locale
import kotlin.reflect.KProperty

/**
 * Created by Rambo 2021/8/17
 * Describe:
 */
inline fun <reified T : Activity> Activity.startActivity(bundle: Bundle? = null) {
    val intent = Intent(this, T::class.java)
    if (bundle != null) {
        intent.putExtras(bundle)
    }
    startActivity(intent)
}

//fun stringOf(@StringRes id: Int, vararg formatArgs: Any): String = getString(id, *formatArgs)
//
//fun stringOf(@StringRes id: Int): String = getString(id)

fun EditText.getNotNullText(): String = text?.toString()?.trim() ?: ""

fun EditText.getNotNullUpperCaseText(): String = getNotNullText().uppercase(Locale.ENGLISH)

//fun getString(@StringRes id: Int, vararg formatArgs: Any?): String {
//    return BaseApp.instance.resources.getString(id, *formatArgs)
//}
//
//fun toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
//    Toast.makeText(BaseApp.instance, message, duration).show()
//}

//may only available on real device
fun EditText.openKeyBoard() {
    val imm = this.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(this, InputMethodManager.RESULT_SHOWN)
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
}

//may only available on real device
fun EditText.hideKeyBoard() {
    val imm = this.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(this.windowToken, 0)
}

fun View.clickWithLimit(intervalMill: Int = 500, block: ((v: View?) -> Unit)) {
    setOnClickListener(object : View.OnClickListener {
        var last = 0L
        override fun onClick(v: View?) {
            if (System.currentTimeMillis() - last > intervalMill) {
                block(v)
                last = System.currentTimeMillis()
            }
        }
    })
}

/**
 * 使用MutableLiveData代理数据，使数据可以被直接赋值而不用再调用value或者postValue
 *
 * 使用例子：var v:Int by activity.mutableLiveDataOf(0){ ... }
 *
 * v = 10086
 */
fun <T> LifecycleOwner.mutableLiveDataOf(value: T, observer: Observer<T>) =
    MutableLiveDataDelegate(value).apply { data.observe(this@mutableLiveDataOf, observer) }

class MutableLiveDataDelegate<T>(defaultValue: T) {
    val data = MutableLiveData(defaultValue)
    operator fun getValue(any: Any?, property: KProperty<*>): T {
        @Suppress("UNCHECKED_CAST")
        return data.value as T
    }

    operator fun setValue(any: Any?, property: KProperty<*>, newValue: T) {
        data.value = newValue
    }
}
